package com.atguigu.dga.ds.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.ds.service.TDsTaskDefinitionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangchen
 * @since 2024-07-31
 */
@Service
@DS("ds")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    @Override
    public List<TDsTaskDefinition> getTaskDefinitionList() {
        List<TDsTaskDefinition> taskDefinitionList = baseMapper.selectDefinitionList();
        //提取每个定义中的sql
        for (TDsTaskDefinition tDsTaskDefinition : taskDefinitionList) {
           String sql=  extractSql(tDsTaskDefinition);
            tDsTaskDefinition.setSql(sql);

        }
        return  taskDefinitionList;

    }


    // 把param 提取出来 转json对象
    // 从json对象提取shell
    // 把shell 掐头去尾
    private String extractSql(TDsTaskDefinition tDsTaskDefinition) {
        //1    // 把param 提取出来 转json对象
        //    // 从json对象提取shell
        String taskParams = tDsTaskDefinition.getTaskParams();
        JSONObject paramJsonObj = JSON.parseObject(taskParams);
        String rawScript = paramJsonObj.getString("rawScript");
        if(rawScript==null){
            return null;
        }
        // 2 把shell 掐头去尾   头部： 优先找with  如果没有找insert  切
        int startIdx = rawScript.indexOf("with"); // indexOf  从字符串中到某个字符串的开始位置
        if(startIdx==-1){
            startIdx = rawScript.indexOf("insert");
        }
        if(startIdx==-1){
            return null;
        }

        int endIdx = rawScript.indexOf(";", startIdx);
        if (endIdx==-1){
            endIdx = rawScript.indexOf("\"", startIdx);
        }
        if(endIdx==-1){
            return null;
        }
        //3 下刀切
        String sql = rawScript.substring(startIdx, endIdx);

        return sql;
    }
}
